<!doctype html>
<html>
<head>
<script type="text/javascript" src="lib/blockad.js"></script>

<script type="text/javascript" src="lib/jquery-3.2.1.min.js"></script>
<script type="text/javascript">

//点击设计费
if (Object.prototype.memberCount == undefined) {
	Object.prototype.memberCount=function(){
		if (typeof(Object.keys) === "function") {
			return Object.keys(this).length;
		}else{
		    var type = Object.prototype.toString.call(this);
		    if(type == '[object Array]'){
		        return this.length;
		    }else if(type === '[object Object]'){
		        var count = 0;
		        for(var i in this){
		        	if (this.hasOwnProperty(i)) {
		        		count++;
		        	}
		        }
		        return count;
		    }else{
		    	return false;
		    }
		}
	}
}

if (Number.prototype.round == undefined) {
	Number.prototype.round=function(n){return parseFloat(this.toFixed(n));}
}


window.alert = function(msg, callback) {
	var div = document.createElement("div");
	div.innerHTML = "<style type=\"text/css\">"
			+ ".nbaMask { position: fixed; z-index: 1000; top: 0; right: 0; left: 0; bottom: 0; background: rgba(0, 0, 0, 0.5); }                                                                                                                                                                       "
			+ ".nbaMaskTransparent { position: fixed; z-index: 1000; top: 0; right: 0; left: 0; bottom: 0; }                                                                                                                                                                                            "
			+ ".nbaDialog { position: fixed; z-index: 5000; width: 80%; max-width: 300px; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); background-color: #fff; text-align: center; border-radius: 8px; overflow: hidden; opacity: 1; color: white; }"
			+ ".nbaDialog .nbaDialogHd { padding: .2rem .27rem .08rem .27rem; }                                                                                                                                                                                                                         "
			+ ".nbaDialog .nbaDialogHd .nbaDialogTitle { font-size: 17px; font-weight: 400; }                                                                                                                                                                                                           "
			+ ".nbaDialog .nbaDialogBd { padding: 0 .27rem; font-size: 15px; line-height: 1.3; word-wrap: break-word; word-break: break-all; color: #000000; }                                                                                                                                          "
			+ ".nbaDialog .nbaDialogFt { position: relative; line-height: 48px; font-size: 17px; display: -webkit-box; display: -webkit-flex; display: flex; }                                                                                                                                          "
			+ ".nbaDialog .nbaDialogFt:after { content: \" \"; position: absolute; left: 0; top: 0; right: 0; height: 1px; border-top: 1px solid #e6e6e6; color: #e6e6e6; -webkit-transform-origin: 0 0; transform-origin: 0 0; -webkit-transform: scaleY(0.5); transform: scaleY(0.5); }               "
			+ ".nbaDialog .nbaDialogBtn { display: block; -webkit-box-flex: 1; -webkit-flex: 1; flex: 1; color: black; text-decoration: none; -webkit-tap-highlight-color: transparent; position: relative; margin-bottom: 0; }                                                                       "
			+ ".nbaDialog .nbaDialogBtn:after { content: \" \"; position: absolute; left: 0; top: 0; width: 1px; bottom: 0; border-left: 1px solid #e6e6e6; color: #e6e6e6; -webkit-transform-origin: 0 0; transform-origin: 0 0; -webkit-transform: scaleX(0.5); transform: scaleX(0.5); }             "
			+ ".nbaDialog a { text-decoration: none; -webkit-tap-highlight-color: transparent; }"
			+ "</style>"
			+ "<div id=\"dialogs2\" style=\"display: none\">"
			+ "<div class=\"nbaMask\"></div>"
			+ "<div class=\"nbaDialog\">"
			+ "	<div class=\"nbaDialogHd\">"
			+ "		<strong class=\"nbaDialogTitle\"></strong>"
			+ "	</div>"
			+ "	<div class=\"nbaDialogBd\" id=\"dialog_msg2\"> 弹窗内容，告知当前状态、信息和解决方法，描述文字尽量控制在三行内</div>"
			+ "	<div class=\"nbaDialogHd\">"
			+ "		<strong class=\"nbaDialogTitle\"></strong>"
			+ "	</div>"
			+ "	<div class=\"nbaDialogFt\">"
			+ "		<a href=\"javascript:;\" class=\"nbaDialogBtn nbaDialogBtnPrimary\" id=\"dialog_ok2\">确定</a>"
			+ "	</div></div></div>";
	document.body.appendChild(div);
 
	var dialogs2 = document.getElementById("dialogs2");
	dialogs2.style.display = 'block';
 
	var dialog_msg2 = document.getElementById("dialog_msg2");
	dialog_msg2.innerHTML = "<br/> "+msg;
 
	// var dialog_cancel = document.getElementById("dialog_cancel");
	// dialog_cancel.onclick = function() {
	// dialogs2.style.display = 'none';
	// };
	var dialog_ok2 = document.getElementById("dialog_ok2");
	dialog_ok2.onclick = function() {
		dialogs2.style.display = 'none';
		callback();
	};
};
</script>
<meta charset="utf-8">
<meta name="viewport" content="width=320, initial-scale=1, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<title>确认订单</title>
<style type="text/css">
* {
    box-sizing: border-box;
    font-family: "Heiti SC","Hiragino Sans GB";
}
a{
	text-decoration: none;
	color: #555;
}
body{
	padding:0;
	margin:0;
	background-color:#F4F4F4;
	font-size:14px;
	color:#444;
}
.visable{
	visibility:visible;
}
.unvisable{
	visibility:hidden;
}
.container{
	width:100%;
	box-shadow: 0 1px 0 #E8E8E8;
	margin-bottom:15px;
	position:relative;
	background-color:#FFF;
}
.one{
	border-bottom:1px solid #E8E8E8;
	display:table;
	width:100%;
	height: 100%;
	table-layout:fixed;
}
.one>div{
	display:table-cell;
}
.item-img{
	width:100px;
	height:100px;
	padding:10px;
}
.item-img img{
	display:block;
	margin:auto;
	max-height:80px;
	max-width:80px;
}
.item-name,.item-price-count{
	height:20px;
}
.price{
	color:red;
}
.price:before{
	color:red;
	content:"¥ ";
}
.count:after{
	content:" 件";
}
.item-sku{
	color:#999;
}
.item-price-count>div{
	display:table-cell;
	white-space:nowrap
}
.item-price{
	width:1%;
}
.item-count{
	text-align:right;
	width:1%;
}
.row{
	display:table;
	border-bottom:1px solid #E8E8E8;
	width:100%;
	table-layout:fixed;
}
.row>div{
	display:table-cell;
	vertical-align:middle;
	padding:10px 10px;
}
.fixed{
	position:fixed;
	bottom:0;
	height:44px;
	background-color:#FFF;
	border-top:1px solid #E8E8E8;
	width:100%;
	display:table;
}
.btn{
	display:table-cell;
	vertical-align:middle;
	text-align:right;
	padding:0 10px;
}
button[type=submit]{
	width:110px;
	height:30px;
	color: #FFF;
	background-color:#B2793D;
	border:1px solid #B2793D;
	border-radius: 8px;
	font-size: 16px;
}
.right-text{
	text-align:right;
}
.title{
	font-weight: bold;
	width:120px;
}
input[name=service],input[name=method]{
	display:none;
}
.check-border{
	display:inline-block;
	border-radius:50%;
	width:18px;
	height:18px;
	border:1px solid #B2793D;
	position: relative;
}
.check-svg{
	transform:translate(-1px,-1px);
	-webkit-transform:translate(-1px,-1px);
	width: 18px;
	position: absolute;
    left: 0;
    top: 0;
}
.row label{
	vertical-align:4px;
	color: #666;
}
#message{
	border: 1px solid #E8E8E8;
	-webkit-appearance: none;
	border-radius: 0;
	vertical-align: middle;
    width:100%;
}
.result{
	width:150px;
	height:auto;
	margin:50px auto;
	font-size:18px;
	color:#888;
}
.result img{
	width:100px;
	opacity:0.4;
}
.result div{
	text-align:center;
}
.warn{
    text-align: center;
    font-size: 20px;
}
.warn a{
	margin-top:100px;
    color:#666;
    text-align: center;
    text-decoration: none;
}
.fastmail>div{
	line-height: 25px;
}
.fastmail .check-label{
	margin-left: 5px;
}
.btn>.message {
	color: red;
    width: calc( 100% - 116px );
    text-align: center;
    font-size: 10px;
}
.btn>.message, .btn>button {
    display: inline-block;
}
</style>
</head>
<body>
<?php
require_once("app-component.php");
$user_id=get_magic_quotes_gpc()?$_POST["user_id"]:addslashes($_POST["user_id"]);
$user_token=get_magic_quotes_gpc()?$_POST["user_token"]:addslashes($_POST["user_token"]);

if(!verify($user_id,$user_token))
{
	echo "<div class='warn'><a href='webView://login'>请登录之后再购买</a></div>";
	return;
}
//去掉查询默认地址id
 
$obj=json_decode($_POST["obj"],true);
foreach ($obj as $type => $value) {
	foreach ($value as $key => $val) {
		$obj[$type][$key]["items"]=parseItem($obj[$type][$key]["items"],true);
	}
}

$user_t=getUserType($user_id);
$user_type=$user_t['user_type'];
$user_type_class=$user_t['user_type_class'];
$user_discount=getUserDiscount($user_type,$user_type_class);
//用户类型显示说明
$sales_help="<div style='line-height:10px;text-align:left;font-size:15px;'>";
if($user_type>=3&&$user_type<=5){
    $sales_help.="<h3>产品合计金额</h3>
       <p>优选产品直接工厂供应价，没有中间商加价。</p>";
}
if($user_type==3||$user_type==4){
    $sales_help.="<h3>服务费</h3>
        <p>平台提供软装产品信息和及时对接各类信息服务，提供免费一年售后咨询服务。</p>";
}
$sales_help.="<h3> 设计费</h3>
<p>用户如果需要全屋软装设计，可以选择委托平台进行设计，满意后支付一定比例的设计费。 </p>";

$sales_help.= "<h3>配送安装</h3>";
if($user_type==3||$user_type==4||$user_type==5){
    $sales_help.= "<p>您在JAJAHOME平台购买的家具商品，配送安装费按实际金额收取。(如商品需搬楼费或吊装上楼，所产生费用按实际情况收取)。</p>";
}else{
    $sales_help.= "<p>您在JAJAHOME平台购买的家具商品，江浙沪地区免费配送。(如商品需吊装上楼，所产生费用按实际情况收取)。
                                            送货上门后，我们会为您提供免费的专业安装服务。
                                            如果因客户自身原因需安排师傅二次上门安装的，可联系客服安排师傅上门服务，按实际金额收取费用。
                                            江浙沪以外的用户如需购买请联系客服，配送安装费可按实际费用多退少补。</p>";
    
}
$sales_help.= "<h3>开具发票</h3>
<p>如对购买的产品需要开具发票，请联系客服400-690-3766。</p>
<h3>品质保证，安心使用</h3>
<p>JAJAHOME软装产品自签收当天起提供一年质量保障，在质保期内如出现质量问题，由JAJAHOME提供免费保修服务。
大部分属于定制商品，不支持无理由退换货。
</p>
</div>";
//用户类型显示说明
//用户服务默认为0（含服务）
// if($user_type<3){
//     $post_sales_service=0;
// }else{
//     $post_sales_service=!empty($user_discount)?($user_discount[1]['service']?$user_discount[1]['service']:0):0;
// }
//所有用户服务都为0（含服务）
$post_sales_service = 0;
$common_vip_discount = getCommonVipDiscount();

$address=getAddress($user_id);
$coupon_type=[
	'0'=>'item',
	'1'=>'set',
	'2'=>'item',
	'3'=>'item',
	'singleItem'=>'item',
	'tz'=>'set',
	'GJJPackage'=>'item',
	'diy'=>'item'
];
$action_arr = [];
$id_count_arr = [];
foreach ($obj as $type => $type_value)
{
	foreach($type_value as $key1 => $value1)
	{
		if (!isset($action_arr[$coupon_type[$type]])){
			$action_arr[$coupon_type[$type]] = [];
		}
		if (!isset($id_count_arr[$coupon_type[$type]])) {
			$id_count_arr[$coupon_type[$type]] =[];
		}
		if ($coupon_type[$type] != 'set')
		{
			foreach($value1["items"] as $key2 => $v)
			{
				$action_arr[$coupon_type[$type]][]=$v['item_id'];
				if(isset($id_count_arr[$coupon_type[$type]][$v['item_id']])){
					$id_count_arr[$coupon_type[$type]][$v['item_id']]=$id_count_arr[$coupon_type[$type]][$v['item_id']]+$v['count'];
				}else{
					$id_count_arr[$coupon_type[$type]][$v['item_id']]=$v['count'];
				}
			}
		}
		elseif ($coupon_type[$type] == 'set')
		{
			$action_arr[$coupon_type[$type]][]=$value1['info']['id'];
			if (isset($id_count_arr[$coupon_type[$type]][$value1['info']['id']])) {
				$id_count_arr[$coupon_type[$type]][$value1['info']['id']]=$id_count_arr[$coupon_type[$type]][$value1['info']['id']]+$value1['info']['count'];
			}else{
				$id_count_arr[$coupon_type[$type]][$value1['info']['id']]=$value1['info']['count'];
			}
		}
		
	}
}
//找出单品和套装优惠券
$coupon=[];
$coupon['item'] = !empty($action_arr['item'])?getItemCoupon($action_arr['item'], $user_id, $id_count_arr['item']):[];
$coupon['set'] =  !empty($action_arr['set'])?getTzCoupon($action_arr['set'], $user_id, $id_count_arr['set']):[];
//找出品牌优惠券
$coupon['brand'] = !empty($action_arr['item'])?getBrandCoupon($action_arr['item'],$user_id, $id_count_arr['item']):[];
$coupon['class'] = !empty($action_arr['item'])?getClassCoupon($action_arr['item'],$user_id, $id_count_arr['item']):[];
//找出全场优惠券
$t = getAllCoupon($user_id);
$coupon['all']   = getAllCoupon($user_id);
$user_ifhas_discount=getIfHasDiscount($user_type, $user_type_class);
if($user_ifhas_discount){
    $user_ifhas_discount=1;
}else{
    $user_ifhas_discount=0;
}
?>
<script type="text/javascript">
var item_info=JSON.parse('<?= $_POST['obj'];?>');
var detail_info = JSON.parse('<?= json_encode($obj)?>');
var user_discount=JSON.parse('<?= json_encode($user_discount);?>');
var cart_type=JSON.parse('<?= json_encode($cart_type);?>');
var coupon = JSON.parse('<?= json_encode($coupon)?>');
var common_vip_discount = <?= $common_vip_discount?>;
var SERVER_PRICE = <?= $GLOBALS['server_price']?>;
var LOGISTICS_PRICE = <?= $GLOBALS['logistics_price']?>;
var DESIGN_PRICE = <?= $GLOBALS['design_price']?>;
 var user_ifhas_discount =<?= $user_ifhas_discount?>;
 var user_type=<?=$user_type?>;
//var user_ifhas_discount=true;
</script>
<style type="text/css">
.address-icon,.item-img{
	vertical-align:middle;
}
.address-info,.item-info{
	vertical-align:top;
}
.address-icon{
	width:50px;
}
.address-icon img{
	display:block;
	margin:auto;
}
.address-info,.item-info{
	padding:10px 10px 10px 0;
}
.address-name-phone{
	margin-bottom:5px;
}
.address-name-phone>div{
	display:table-cell;
}
.address-name{
	width:70%;
	word-break:break-all;
	word-wrap:break-word;
}
.address-tel{
	text-align:right;
	width:1%;
}
.address-detail{
	word-break:break-all;
	word-wrap:break-word;
}
.address-d{
	position: relative;
	background-color: #FFF;
	transform: translate3d(0, 0, 0);
	-webkit-transform: translate3d(0, 0, 0);
	backface-visibility: hidden;
	-webkit-backface-visibility: hidden;
}
.address-d.active{
	z-index: 99;
}
.show:not(.active){
	animation-name: flodin;
	animation-duration: 0.25s;
	animation-timing-function:linear;
	animation-fill-mode: forwards;
	-webkit-animation-name: flodin;
	-webkit-animation-duration: 0.25s;
	-webkit-animation-timing-function:linear;
	-webkit-animation-fill-mode: forwards;
	display: block;
}
.hide:not(.active){
	height: 0;
	display: none;
}
@keyframes flodin{
	0%  {height: 0;opacity: 0;}
	100%{height: 89px; opacity: 1;}
}
.item-discount,.tz-discount{
	color:#999999;
	display:inline-block;
}
.item-discount{
	margin-right:10px;
}
.warn{
	padding:5px;
	height: 40px;
    line-height: 28px;
    background-color: rgba(255,0,0,0.1);
    border: 1px solid rgba(255,0,0,0.4);
    color: #F00;
}
.warn a{
	color:#F00;
	text-decoration:none;
}
.discount,.lead_time{
	display: table-cell;
	color: #999999;
}
.blank{
	height: 44px;
	width: 100%;
}
.install-method .check-border{
	vertical-align: top;
}
.install-method .check-label{
	margin-left: 5px;
	width: calc(100% - 25px);
	display: inline-block;
}
.check-label{
	color: #666;
}
.coupon-left{
	width: 120px;
	font-size: 0;
}
.coupon-left>div{
	display: table-cell;
}
.coupon-radio{
	vertical-align: middle;
}
.coupon_all_radio{
    vertical-align: middle;
}
.coupon-left img{
	max-width: 90px;
	max-height: 90px;
}
.clean_coupon{
	float: right;
    border: 1px solid #CCC;
}
.chk-div {
    width: 30px;
}
.show-price{
	line-height: 20px;
	width: 100%;
    display: inline-block;
    text-align: right;
}
input::-webkit-input-placeholder{
	color:#999999;
	font-size:14px; 
}<!---webkit-appearance:none;-->
input {
cursor: pointer;

	border-radius:0;
}
</style>
<div class="container address-container">
	<?php if(empty($address)):?>
    <div class="warn">您还没有地址&nbsp;&nbsp;&nbsp;&nbsp;<a href="webView://address">去添加地址>></a></div>
    <?php else:?>
    	<?php
    		$default_address=false;
    		for($i=count($address)-1;$i>=0;$i--)
	    	{
	    		if ($address[$i]["default"]) {
	    			$default_address=true;
	    		}
    		}
    		if (!$default_address) {
    			$address[0]['default']=1;
    		}
    	?>
    	<?php for($i=0;$i<count($address);$i++):?>
			<?php if($address[$i]["default"]):?>
	        <div class="address-d active hide" data-id="<?= $address[$i]["id"]?>">
	            <div class="address-t one">
	                <div class="address-icon">
	                	<img src="images/location-icon.png" width="36" class="visable">
	                </div>
            <?php else:?>
	        <div class="address-d hide" data-id="<?= $address[$i]["id"]?>">
	            <div class="address-t one">
	                <div class="address-icon">
	                	<img src="images/location-icon.png" width="36" class="unvisable">
	                </div>
            <?php endif;?>
	                <div class="address-info">
	                    <div class="address-name-phone">
	                        <div class="address-name"><?= $address[$i]["name"]?></div>
	                        <div class="address-tel"><?= $address[$i]["mobile"]?></div>
	                        <input type="hidden" name="address_id" value="<?= $address[$i]["id"]?>">
	                    </div>
	                    <div class="address-detail">
	                        <?= $address[$i]["city"]."<br>".$address[$i]["detail"]?>
	                    </div>
	                </div>
            	</div>
      		</div>
        <?php endfor;?>
    <?php endif;?>
</div>



  <input id="address_id" value="<?=$adddress_default_id?>" type="hidden">

<div class="container item-container">	
</div>

<div class="container coupon-container">
</div>

<div class="container orderinfo-container">
	<div class="row">
    	<div class="title">结算费用选择</div>
    </div>
     <div class="row">
    	<div class="title">合计件数  </div>
        <div class="count right-text" id="item_total_count"></div>
    </div>
     <div class="row">
    	<div class="title" style="width:250px;">产品合计金额
    	
    	<a><img  style="margin-left:50px;" width="20px"  height="20px" src="images/check-icon.png"/></a>
    		<a href="#" onclick="redirect_why(<?=$user_type?>);"><img  style="margin-left:20px;" width="20px"  height="20px" src="images/why.png"/></a>
    	
    	</div>
      	<div><span class="good-price show-price" name="good"></span></div>
    </div>
        <!-- 服务费代码块-->
        <!--刘文霞2021-4-8修改  （判断服务费，小于等于0则不显示）-->
      <?php if(($user_type==3||$user_type==4)&&$GLOBALS['server_price']>0):?>
            <div class="row" >
                <div class="title" style="width:250px;">服务费
                     <?=$GLOBALS['server_price']?>%
                     <img  style="margin-left:62px;" width="20px"  height="20px" src="images/check-icon.png">
                    <a  href="#" onclick="redirect_why(<?=$user_type?>);"><img  style="margin-left:20px;" width="20px"  height="20px" src="images/why.png"/></a>
                </div>
                <div><span class="server-price show-price"></span></div>
            </div>
      <?php else:?>
      <!--刘文霞2021-4-8修改 （避免js计算价格报错，隐藏显示server-price show-price的价格div）-->
             <div style="display: none;"><span class="server-price show-price"></span></div>
      <?php endif;?>
        <!--设计费代码块-->
       <?php if( $GLOBALS['design_price']>0):?>
               <div class="row">
                   <div class="title" style="width:250px;">设计费

                           <?=$GLOBALS['design_price']?>%
                           <img  style="margin-left:72px;"  class="checkbox"    id="design_checkimg" width="20px"  height="20px" src="images/unchecked.png" onclick="design_checkclick();">
                          <input  id="design_agree" style="display:none;"  type="checkbox"  name="design"  >
                          <a  href="#" onclick="redirect_why(<?=$user_type?>);"><img  style="margin-left:18px;" width="20px"  height="20px" src="images/why.png"/></a>
                   </div>
                   <!-- <div class="chk-div"></div> -->
                   <div><span class="design-price show-price"  style="color:red;"></span></div>
               </div>
        <!--刘文霞2021-4-8修改 （避免js计算价格报错，隐藏显示design-price show-price的价格div）-->
       <?php else:?>
           <input  id="design_agree" style="display:none;"  type="checkbox"  name="design"  >
             <div><span class="design-price show-price"  style="color:red;"></span></div>
        <?php endif;?>
        <!--配送安装-->
        <div class="row" >        
            <div class="title"  style="width:80px;">配送安装


            </div>
            <!-- <div class="chk-div"></div> -->
            <div>
                <!--vip用户 (3、4 )运营商(5)到付，普通用户江浙沪包邮 -->
                <?php if($user_type==3||$user_type==4||$user_type==5):?>
                    <span class="install-price show-price"  style="color:red;font-size:12px;">按实际金额到付</span>
                <?php else:?>
                    <span class="install-price show-price"  style="color:red;font-size:12px;">江浙沪包配送安装，超出区域按实际支付</span>
                <?php endif?>
            </div>
        </div>

 
<script type="text/javascript">
//点击跳转帮助说明
function redirect_why(user_type){
window.location.href="sales_help.php?user_type="+user_type;
	
}

//点击物流安装费
function install_checkclick(){   
	   var checkimg = document.getElementById("install_checkimg"); 
	   if(document.getElementById("install_agree").checked==true ){
		   document.getElementById("install_agree").checked=false;
		   var test=document.querySelector('input[name="install"]').checked;
		   checkimg.src="images/unchecked.png"; 
		}else{
			 document.getElementById("install_agree").checked=true;
			var test=document.querySelector('input[name="install"]').checked;
			 checkimg.src="images/check-icon.png"; 
		}
			//重新计算物流安装费
			item.calc();
	 
	}  
//点击设计费	
function  design_checkclick(){
	var checkimg = document.getElementById("design_checkimg"); 
	   if(document.getElementById("design_agree").checked==true ){
		   document.getElementById("design_agree").checked=false;
		   checkimg.src="images/unchecked.png"; 
		}else{
			 document.getElementById("design_agree").checked=true;
			 checkimg.src="images/check-icon.png"; 
		}
			//重新计算物流安装费
			item.calc();
	
}
// lwx  
function addServiceprice(){
	var ifusecoupon=parseInt(document.getElementById("ifusecoupon").value);
	var recordtotalprice=parseInt(document.getElementById("recordtotalprice").value);
	  var expenseprice=parseInt(document.getElementById("expenseprice").value);
	 var couponprice=parseInt(document.getElementById("couponprice").value);
	 if(expenseprice==0){
			//计算物流费
			expenseprice=parseInt(document.getElementById("recordexpenseprice").value);
			document.getElementById("expenseprice").value=expenseprice;
	    }
	 //设置含物流价格
	 var recordprice=recordtotalprice+expenseprice; 
	 document.getElementById("recordprice").value=recordprice;
	if(ifusecoupon==1){
		var realprice=couponprice+expenseprice;  
    }else{
    	var realprice=parseInt(recordtotalprice+expenseprice);   
     }
	document.querySelector('#item_total_price').textContent = parseInt(realprice);
	document.getElementById("service_state").value=0;
}
// lwx 服务自理 直接单品原价就行 
function removeServiceprice(){
	var ifusecoupon=parseInt(document.getElementById("ifusecoupon").value);
	var recordprice=document.getElementById("recordprice").value;
	var expenseprice=parseInt(document.getElementById("expenseprice").value);
	if(expenseprice==0){
		//计算物流费
		expenseprice=document.getElementById("recordexpenseprice").value;
		document.getElementById("expenseprice").value=expenseprice;
    }
	var realprice=recordprice-expenseprice;
	 var couponprice=parseInt(document.getElementById("couponprice").value);
	if(ifusecoupon==1){
		realprice=couponprice;
     }else{
    	 realprice=parseInt(document.getElementById("recordtotalprice").value);
     }
	document.querySelector('#item_total_price').textContent =realprice;
	document.getElementById("service_state").value=1;
}
</script>      
    <!-- 新增 是否含服务  -->
   
    <div class="row">
    	<div class="title">总计金额</div>
            <!-- lwx  记录金额，服务状态，   不可删除 -->
            <!-- 不含物流费价格: --><input type="hidden" name="recordtotalprice" id="recordtotalprice" value="0"/>
            <!-- 服务费: -->		<input type="hidden" name="expenseprice" id="expenseprice" value="0"/>
            <!-- 服务状态绑定价格:--><input type="hidden" name="recordprice" id="recordprice" value="0"/>
            <!-- 服务状态: -->	<input type="hidden" id="service_state" value="<?php echo $post_sales_service;?>"/>
            <!-- 使用优惠券价格: --><input type="hidden" name="couponprice" id="couponprice" value="0"/>
            <!-- 是否使用优惠券： --><input type="hidden" name="ifusecoupon" id="ifusecoupon" value="0"/>
            <!-- 服务费用 -->		<input type="hidden" name="recordexpenseprice" id="recordexpenseprice" value="0"/>
            <!-- 物流安装费 -->    <input type="hidden" name="installprice" id="installprice" value="0"/>
            <!-- 设计费 -->	    <input type="hidden" name="designprice" id="designprice" value="0"/>
        <div class="price right-text" id="item_total_price"  style="color:red;">
        </div>
    </div>
    <div class="row">
    	<div class="title">买家留言</div>
        <div class="right-text"><textarea id="message" onblur="messageBur()"></textarea></div>
    </div>
    
</div>

<div class="blank"></div>
<div class="fixed">
    <div class="btn">
    	<div class="message"></div>
    	<button type="submit" onClick="checkAddress()">提交订单</button>
    </div>
</div>
<script type="text/javascript">
//点击帮助说明，跳转页面
function  look_help(){
	 setTimeout(function(){location.href='webView://sales_help.html'},1000);
}
function messageBur(){
	document.querySelector("button.clean_coupon").setAttribute("disabled",true);
	var coupon_item=document.querySelectorAll(".coupon-item");
	var radio=document.querySelectorAll("input[type='radio']");
	for(var i=0;i<radio.length;i++){
		radio[i].setAttribute("disabled","disabled");
	}
	for(var j=0;j<coupon_item.length;j++){
		coupon_item[j].setAttribute("disabled","disabled");
	}
	setTimeout(function(){
		document.querySelector("button.clean_coupon").removeAttribute("disabled");
		for(var i=0;i<radio.length;i++){
			radio[i].addAttribute("disabled");
		}
		for(var j=0;j<coupon_item.length;j++){
			coupon_item[j].removeAttribute("disabled");
		}
	},1000)
}
var addressExpand=0;//0:关闭状态，1:展开状态
function bindAddress()
{
	var address=document.querySelectorAll(".address-d");
	for(var i=0;i<address.length;i++)
	{
		address.item(i).addEventListener("click",function(){
			var address=document.querySelectorAll(".address-d");
			if(addressExpand==0&&this.classList.contains("active"))
			{
				for(var i=0;i<address.length;i++)
				{
					address.item(i).classList.remove("hide");
					address.item(i).classList.add("show");
				}
				addressExpand=1;
			}
			else if(addressExpand&&this.classList.contains("active"))
			{

				for(var i=0;i<address.length;i++)
				{
					address.item(i).classList.remove("show");
					address.item(i).classList.add("hide");
				}
				addressExpand=0;
			}
			else if(addressExpand&&(!this.classList.contains("active")))
			{

				for(var i=0;i<address.length;i++)
				{
					address.item(i).classList.remove("show");
					address.item(i).classList.remove("active");
					address.item(i).classList.add("hide");
				}
				this.classList.add("active");
				var tt=document.querySelector("img[class=visable]")
				tt.classList.remove("visable");
				tt.classList.add("unvisable");
				this.querySelector("img").classList.remove("unvisable");
				this.querySelector("img").classList.add("visable");
				addressExpand=0;
                var addressid=document.querySelector(".address-d.active").dataset.id;
                //lwx 11.4 选择了地址之后 设置地址id
                $("#address_id").val(addressid);
			}
		});
	}
}
var check_coupon=[];
window.onload=function(){
	bindAddress();
	bindCoupon();
};
function bindCoupon()
{
	var coupon_item = document.querySelectorAll('input[name="item-radio"],input[name="set-radio"]');
	for(var i=0; i<coupon_item.length; i++)
	{
		coupon_item[i].onchange = changeCoupon;
	}
}
//点击提交订单 格式化收货地址  传递参数到suumitorder函数
function checkAddress()
{
	//lwx 8.8 新增 传递物流安装费 installprice  设计费  designprice
 //	var installprice=document.querySelector('#installprice').value;
    var installprice=0;
	 var designprice=document.querySelector('#designprice').value;
 	var address=document.querySelector('.address-d.active .address-detail').innerHTML;
	if (address.indexOf('<br>')) {
		address=address.split('<br>')[0].replace(/(^\s*)|(\s*$)/g,"").split(' ');
	}else{
		address=address.replace(/(^\s*)|(\s*$)/g,"").split(' ');
	}
	var last=address[address.length-1];
	var fd=new FormData();
	fd.append('q','check-address');
	fd.append('address',last);
	fd.append("user_id","<?= $user_id?>");
	fd.append("user_token","<?= $user_token?>");
	//lwx 8.8 新增 传递物流安装费 installprice  设计费  designprice
	fd.append('installprice',installprice);
	fd.append('designprice',designprice);
	//传递参数跳转到submitorder函数
	var xhr = new XMLHttpRequest(); 
	var submitorder_data=submitOrder();
/* 	xhr.onreadystatechange = function(){
		if (xhr.readyState === 4 && xhr.status === 200)
		{
			alert("success...");
				submitOrder();
		}else{
		    alert("error...");
		}
	}; */
	xhr.open('POST', 'calc.php', true);
	xhr.send(submitorder_data);
}
 //提交订单
function submitOrder()
{

	 //验证字符串长度函数
	 var memo_state=true;
	 var jmz = {};
	    jmz.GetLength = function(str) {
	        ///<summary>获得字符串实际长度，中文2，英文1</summary>
	        ///<param name="str">要获得长度的字符串</param>
	        var realLength = 0, len = str.length, charCode = -1;
	        for (var i = 0; i < len; i++) {
	            charCode = str.charCodeAt(i);
	            if (charCode >= 0 && charCode <= 128)
	                realLength += 1;
	            else
	                realLength += 2;
	        }
	        return realLength;
	    };
	//验证单品备注不能超过20个
	var memo=document.getElementsByName("memo[]");
	for(var i=0;i<memo.length;i++){
		var memotext=memo[i].value;
		var strlen=jmz.GetLength(memotext);
		 if(strlen>100){
			 memo_state=false;
		        alert("单品备注字数长度不能大于50个");
		        return false;break;
		    }
	}
	if(!memo_state){
		//数据错误 不可提交订单
		return false;
	}else{
		//提交订单
		var userInfo={};
		userInfo["message"]=document.getElementById("message").value;
		
		if (document.querySelector(".address-d.active")!=null&&document.querySelector(".address-d.active").dataset.id) {
			userInfo["address_id"]=document.querySelector(".address-d.active").dataset.id;
		}
		else{
			return;
		}
		var design = document.querySelector('input[name=design]:checked');
		var coupon = document.querySelectorAll('.coupon-container input[type=radio]:checked');

	   //lwx 新增 服务费 物流费 设计费
		//var installprice=document.querySelector('#installprice').value;
	    var installprice=0;
		 var designprice=document.querySelector('#designprice').value;
		 var expenseprice=document.getElementById("expenseprice").value;
		var a=[];
		for (var i = 0,j = 0; i < coupon.length; i++) {
			a[j++]=coupon[i].dataset.user_coupon_id;
		}
		
		var fd=new FormData();
		fd.append("q","submitOrder");
		fd.append("item_info",JSON.stringify(item_info));
		fd.append("user_info",JSON.stringify(userInfo));
		fd.append("user_id",<?= $user_id?>);
		fd.append("user_token","<?= $user_token?>");
		//添加物流费 设计费
		fd.append("installprice",installprice);
		fd.append("designprice",designprice);
		fd.append("expenseprice",expenseprice);

		// 3/4 新增备注
	    var memolist=document.getElementsByName("memo[]");
	    var memoarray=new Array();
	    for(var i=0;i<memolist.length;i++){
	        memoarray.push(memolist[i].value);
	    }
	    fd.append("item_memo",memoarray);
		var coupon = [], i=0;
		c.itemCoupon?coupon[i++]=c.itemCoupon.id:'';
		c.tzCoupon?coupon[i++]=c.tzCoupon.id:'';
		c.allCoupon?coupon[0] = c.allCoupon.id:'';
		fd.append("coupon",JSON.stringify(coupon));
		//lwx 新增
		var service_state=document.getElementById("service_state").value;//服务状态
		var goodprice= parseInt(item.total_price);//商品总价
		fd.append('post_sales_service',service_state);
		var recordtotalprice=parseInt(document.getElementById("recordtotalprice").value);
		var expenseprice=parseInt(document.getElementById("expenseprice").value);
		var recordprice=parseInt(document.getElementById("recordprice").value);
		//var realprice=recordtotalprice+expenseprice;  
		var good_last_price=parseInt(recordprice);  
		var ifcoupon=parseInt(document.getElementById("ifusecoupon").value);
		var couponprice=parseInt(document.getElementById("couponprice").value);
		if(ifcoupon==1){
			recordprice=couponprice+expenseprice;
			good_last_price=parseInt(recordprice); 
			
		}else{
			//没有使用优惠券  
			good_last_price=parseInt(recordprice); 
		}

		 //最终价格为显示的价格
		 good_last_price= document.querySelector('#item_total_price').textContent;
		//fd.append("sales_logistics",document.querySelector('input[name="install"]').checked?'0':'1');
	    fd.append("sales_logistics",1);
		fd.append("sales_design", 	document.querySelector('input[name="design"]').checked?'0':'1');
		fd.append("total_price",good_last_price);

		/* var html="<div class=\"result\"><div><img src=\"images/success.png\"></div><div>订单提交成功</div></div>";//订单提交成功
		  document.body.innerHTML=html; */
		  var xhr = new XMLHttpRequest();
	 
		xhr.onreadystatechange = function(){
			if (xhr.readyState === 4)
			  {
				if (xhr.status === 200)
				{
			    	 var response=JSON.parse(xhr.responseText);
			    	 //var response=xhr.responseText;
					 trade_no=response.trade_no;
				  if(response.state) {
					  var html="<div class=\"result\"><div><img src=\"images/success.png\"></div><div>订单提交成功</div></div>";//订单提交成功
					  setTimeout(function(){location.href='webView://order?order_id='+trade_no},1000);//跳转至付款页面
				  }
				  else
				   {
				 	  var html="<div class='result'><div><img src='images/failed.png'></div><div>订单提交失败<br><a href='webView://close'>重新选择</a></div></div>";
				  }
				  document.body.innerHTML=html;
				}
				else
				{
					
					console.error(xhr.statusText);
				}
			  }else{
					  //  alert(xhr.responseText);
			 }
	    	
		}; 
		
		xhr.open('POST', 'calc.php', true);
		xhr.send(fd);

	}
	 
	
	
	
}

var Item = function(){
	this.itemList = {};
	this.conatiner = document.querySelector('.item-container');
	this.userDiscount = null;
	this.itemCoupon = null;
	this.tzCoupon = null;
	this.allCoupon = null;
	this.itemObj = null;
};
Item.prototype.create = function(obj){
	var uid = obj.uid;
	var sku_name = {'mat':'材质', 'fab':'面料', 'size':'尺寸'};
	this.total_price = 0;
	this.itemList[uid] = {};

	var sku_str = '';
	if (obj.sku != null) {
		for (var i in obj.sku) {
			if (obj.sku.hasOwnProperty(i)) {
				if (i === 'size') {
					continue;
				}else{
					sku_str = sku_str + sku_name[i]+':'+obj.sku[i];
				}
			}
		}
		if (typeof(obj.sku.size)!='undefined') {
			sku_str = sku_str + (sku_str!=''?'<br>':'') + '尺寸:'+obj.sku.size;
		}
	}
	
	this.itemList[uid].node = document.createElement('div');
	this.itemList[uid].node.classList.add('item');
	this.itemList[uid].node.classList.add('one');
	this.itemList[uid].node.innerHTML = '<div class="item-img">'+
			'<img src="<?= $url.$path?>'+obj.img_url+'">'+
		'</div>'+
		'<div class="item-info">'+
			'<div class="item-name">'+obj.name+'</div>'+
            '<div class="item-price-count">'+
            	'<div class="item-price price"></div>'+
            	'<div class="item-count count">'+obj.calc_count+'</div>'+
            '</div>'+
            '<div class="item-sku">'+sku_str+'</div>'+
        	'<div class="discount"></div>'+
        	'<div class="lead_time">'+(obj.lead_time?'供货周期:'+obj.lead_time+';':'')+'</div>'+
            '<div  style="margin-top:5px;color:#E8E8E8;font-size:14px; ">  <textarea  style="width:230px;height:30px;border:1px solid #E8E8E8;" placeholder="备注限50个字" name="memo[]"  ></textarea>  </div>'+
		'</div>';
};
//onblur="check_itemmemo(this)"
Item.prototype.check_coupon = function(coupon_type, coupon_obj){ 
	this.coupon = {
		type:coupon_type,
		obj:coupon_obj,
	}
};
Item.prototype.calc = function(){

	var sales_type_map 		= {singleItem:1, tz:2};
	var use_coupon 			= false;
	var item_total_price 	= 0;
	var tz_total_price 		= 0;

	var total_class_price 	= 0;
	var total_brand_price 	= 0;
	var total_all_price	  	= 0;

	var total_old_price   	= 0;//lwx新增  计算订单单品原价

	var total_price 		= 0;
	var total_count 		= 0;
	for (var type in this.itemObj) {
		if (type == 'singleItem') {
			for (var i = 0; i < this.itemObj[type].length; i++) {
				var info = this.itemObj[type][i].info;
				info.type = type;
				typeof(info.exclude) ==='undefined'?info.exclude = [] : '';
				for (var j = 0; j < this.itemObj[type][i].items.length; j++) {
					var discount = '';
					var item = this.itemObj[type][i].items[j];
					var uid = typeof(item.uid)!='undefined'?item.uid:(type + '' + parseInt(Math.random()*100000000));
					
					Object.prototype.toString.call(item.count)=='[object String]'?item.count = parseInt(item.count):'';
					Object.prototype.toString.call(item.price_base)=='[object String]'?item.price_base = parseFloat(item.price_base):'';
					Object.prototype.toString.call(item._price_custom)=='[object String]'?item._price_custom = parseFloat(item._price_custom):'';
					Object.prototype.toString.call(item.price_discount)=='[object String]'?item.price_discount = parseFloat(item.price_discount):'';
					Object.prototype.toString.call(item._price_discount)=='[object String]'?item._price_discount = parseFloat(item._price_discount):'';
					item.uid = uid;
					item.calc_count = item.count;

					//判断单品优惠券
					if(this.itemCoupon && this.itemCoupon.action == 'item' && (this.itemCoupon.action_id == item.item_id || this.itemCoupon.action_id == 0) && !use_coupon){
						item.final_price = item.price_base + item._price_custom;
						item_total_price = item_total_price + this.coupon_calc((item.price_base + item._price_custom), item.count, this.itemCoupon);
						use_coupon = true;
						discount = '单品优惠券; ';
					}
					//存在类目优惠券
					else if (this.itemCoupon && this.itemCoupon.action == 'class' && item.class_id == this.itemCoupon.action_id) {
						item.final_price = item.price_base + item._price_custom;
						total_class_price = total_class_price + item.final_price * item.count;
						discount = '类目优惠券; ';
					}
					//存在品牌优惠券
					else if (this.itemCoupon && this.itemCoupon.action == 'brand' && item.brand_id == this.itemCoupon.action_id) {
						item.final_price = item.price_base + item._price_custom;
						total_brand_price = total_brand_price + item.final_price * item.count;
						discount = '品牌优惠券; ';
					}
					//存在全场优惠券
					else if (this.allCoupon && this.allCoupon.action == 'all') {
						item.final_price = item.price_base + item._price_custom;
						total_all_price = total_all_price + item.final_price * item.count;
						discount = '全场优惠券; ';
					}
					//存在用户折扣
					else if (this.userDiscount.memberCount()) {
						discount = parseFloat(this.userDiscount[sales_type_map[type]].discount);
						item.final_price = item.price_base?((item.price_base + item._price_custom)*discount).round(2):0;
						item_total_price = item_total_price + item.final_price*item.count;
						discount = '用户折扣:'+discount+'; ';
					}
					//否则计算单品本身折扣
					else {
						item.final_price = item.price_base?(item.price_base*item.price_discount + item._price_custom*item._price_discount).round(2):0;
						item_total_price = item_total_price + item.final_price*item.count;
						discount='';
					}
					//lwx添加
					total_old_price=total_old_price+item.count*(item.price_base+item._price_custom).round(2);
					typeof(this.itemList[uid])=='undefined'?this.create(item):'';
					this.itemList[item.uid].node.querySelector('.price').textContent = item.final_price||!in_array(item.item_id, info.exclude)?item.final_price:'请询价';
					this.itemList[item.uid].node.querySelector('.discount').textContent = discount;
				}
				total_count = total_count + item.count;
			}
			
			total_price = total_price + item_total_price;
			
			//单品类目优惠
			if (total_class_price && this.itemCoupon && this.itemCoupon.action == 'class') {
				total_price = total_price + this.coupon_calc(total_class_price, 1, this.itemCoupon);
			}
			//单品品牌优惠
			if (total_brand_price && this.itemCoupon && this.itemCoupon.action == 'brand') {
				total_price = total_price + this.coupon_calc(total_brand_price, 1, this.itemCoupon);
			}
		}else if (type == 'tz') {
			var max_tz_index = 0;
			var max_tz_price = 0;

			var max_action_tz_index = 0;
			var max_action_tz_price = 0;
			
			for (var i = 0; i < this.itemObj[type].length; i++) {
				var info = this.itemObj[type][i].info;
				info.type = type;
				typeof(info.exclude) ==='undefined'?info.exclude = [] : '';
				info.final_price = 0;
				info.origin_price = 0;
				var t_count = 0;
				
				for (var j = 0; j < this.itemObj[type][i].items.length; j++) {
					var discount = '';
					var item = this.itemObj[type][i].items[j]; 
					var uid = typeof(item.uid)!='undefined'?item.uid:(type + '' + parseInt(Math.random()*100000000));

					Object.prototype.toString.call(item.count)=='[object String]'?item.count = parseInt(item.count):'';
					Object.prototype.toString.call(item.price_base)=='[object String]'?item.price_base = parseInt(item.price_base):'';
					Object.prototype.toString.call(item._price_custom)=='[object String]'?item._price_custom = parseInt(item._price_custom):'';
					Object.prototype.toString.call(item.price_discount)=='[object String]'?item.price_discount = parseFloat(item.price_discount):'';
					Object.prototype.toString.call(item._price_discount)=='[object String]'?item._price_discount = parseFloat(item._price_discount):'';
					item.uid = uid;

					if (in_array(item.item_id, info.exclude)) {
						item.final_price = 0;
					}
					//用户折扣
					else if (this.userDiscount.memberCount() && parseFloat(user_discount[cart_type[type]]['discount'])>0) {
						discount = parseFloat(user_discount[cart_type[type]].discount);
						item.final_price = ((item.price_base+item._price_custom)*discount).round(2);
						info.final_price = info.final_price + item.final_price*item.count*info.count.round(2);
						discount=(discount!=1?'用户折扣:'+discount+'; ':'');
					}
					//套装折扣
					else if (info.discount != undefined && parseFloat(info.discount) > 0 && parseFloat(info.discount) < 1) {
			 			discount = parseFloat(info.discount);
						/*
						item.final_price = ((item.price_base+item._price_custom)*discount).round(2);
						*/
						item.final_price = ((item.price_base*item.price_discount+item._price_custom*item._price_discount)*discount).round(2);
						info.final_price = info.final_price + item.final_price*item.count*info.count.round(2);
						discount=(discount!=1?'套装折扣:'+discount+'; ':'');
					}
					else{
						item.final_price = (item.price_base*item.price_discount+item._price_custom*item._price_discount).round(2);
						info.final_price = info.final_price + item.final_price * item.count * info.count.round(2);
						discount='';
					}
					//计算全场优惠券用到的原价总和
                    if (this.allCoupon && this.allCoupon.action == 'all'){
                    					if (!in_array(item.item_id, info.exclude)) {
                    						item.final_price = item.price_base + item._price_custom;
                    						total_all_price = total_all_price + item.final_price * item.count * info.count.round(2);
                    					}  
                    }
					t_count = t_count + item.count * info.count;
					!in_array(item.item_id, info.exclude)?info.origin_price = info.origin_price + ((item.price_base+item._price_custom)*item.count).round(2):'';
					//lwx 新增
					if (!in_array(item.item_id, info.exclude)) {
						total_old_price=total_old_price+item.count*(item.price_base+item._price_custom) * info.count.round(2); 
					} 
					typeof(this.itemList[item.uid])=='undefined'?this.create(item):'';

					this.itemList[item.uid].node.querySelector('.price').textContent = item.final_price||!in_array(item.item_id, info.exclude)?item.final_price:(in_array(item.item_id, info.exclude)?'赠品':'请询价');
					this.itemList[item.uid].node.querySelector('.discount').textContent = discount;
					this.itemList[item.uid].node.querySelector('.count').textContent = item.count * info.count;
				}

				total_count = total_count + t_count;
				tz_total_price = tz_total_price + info.final_price;
				//筛选出最大价格的套装
				if (info.final_price > max_tz_price) {
					max_tz_price = info.final_price;
					max_tz_index = i;
				}
				//筛选出最大价格的指定id的套装
				if (this.tzCoupon && this.tzCoupon.action_id == info.id) {
					if (info.final_price > max_action_tz_price) {
						max_action_tz_price = info.final_price;
						max_action_tz_index = i;
					}
				}
			}
			//指定套装id的优惠券计算
			if (this.tzCoupon && this.tzCoupon.action_id == this.itemObj[type][max_action_tz_index].info.id) {
				discount='套装优惠券;';
				var info = this.itemObj[type][max_action_tz_index].info;
				tz_total_price = tz_total_price - info.final_price;
				
				for(var j=0; j < this.itemObj[type][max_action_tz_index]['items'].length; j++)
				{
					item = this.itemObj[type][max_action_tz_index]['items'][j];
					if (in_array(item.item_id, info.exclude)) {
						this.itemList[item.uid].node.querySelector('.price').textContent = '赠品';
					}else{
						this.itemList[item.uid].node.querySelector('.price').textContent = (item.price_base + item._price_custom).round(2);
					}
					this.itemList[item.uid].node.querySelector('.discount').textContent = discount;
				}
				info.final_price = this.coupon_calc(info.origin_price, info.count, this.tzCoupon);
				tz_total_price = tz_total_price + info.final_price;
				use_coupon = true;
			}

			if (this.tzCoupon && this.tzCoupon.action_id == 0){
				discount='套装优惠券;';
				var info = this.itemObj[type][max_tz_index].info;
				tz_total_price = tz_total_price - info.final_price;

				for(var j=0; j < this.itemObj[type][max_tz_index]['items'].length; j++)
				{
					item = this.itemObj[type][max_tz_index]['items'][j];
					if (in_array(item.item_id, info.exclude)) {
						this.itemList[item.uid].node.querySelector('.price').textContent = '赠品';
					}else{
						this.itemList[item.uid].node.querySelector('.price').textContent = (item.price_base + item._price_custom).round(2);
					}
					this.itemList[item.uid].node.querySelector('.discount').textContent = discount;
				}
				info.final_price = this.coupon_calc(info.origin_price, info.count, this.tzCoupon);
				tz_total_price = tz_total_price + info.final_price;
			}

			total_price = total_price + tz_total_price;
		}
	}
	//lwx 增加
	//服务状态
	var service_state = document.getElementById("service_state").value;
	//服务费
	var expenseprice = document.getElementById("expenseprice").value;
	//是否使用优惠券
	var ifusecoupon = document.getElementById("ifusecoupon").value;//使用优惠券状态
    //记录服务费 
    var recordexpenseprice = 0;
    if(total_old_price>0){
    	recordexpenseprice = parseInt(total_old_price * common_vip_discount *  (SERVER_PRICE/100));
	} 
    document.getElementById("recordexpenseprice").value = recordexpenseprice;
    document.querySelector('#item_total_count').textContent = total_count;
	//全场优惠券
	if (this.allCoupon) {
		total_price = this.coupon_calc(total_all_price, 1, this.allCoupon);
		
		//使用优惠券，获取使用优惠券金额
		document.getElementById("couponprice").value = total_price;
		
        if(total_old_price > 0){
            //9/17 用户不存在折扣，不存在服务费 设置为0
            if(user_type==3||user_type==4){
            	expenseprice = parseInt(total_old_price * common_vip_discount *  (SERVER_PRICE/100));
            }else{
            	expenseprice=0;
            }
         }
        
        //设置服务费用
        document.getElementById("expenseprice").value = expenseprice;
        document.getElementById("recordprice").value = total_price + expenseprice;
        
        //使用了优惠券
        if(ifusecoupon == 1){
            var couponprice = document.getElementById("couponprice").value;
            document.querySelector('#item_total_price').textContent = parseInt(couponprice)+expenseprice;
        }else{
        	document.querySelector('#item_total_price').textContent = parseInt(total_price)+expenseprice;
        }
	//不是全场优惠券
	}else{
		document.getElementById("couponprice").value = parseInt(total_price);
	 	
		var couponprice=document.getElementById("couponprice").value;

		 //计算服务费
        //9/17   用户不存在折扣，不存在服务费
		 //11.5 vip（3,4）存在服务费 其他类型无服务费
		 if(user_ifhas_discount&&(user_type==3||user_type==4)){
				expenseprice = parseInt(total_old_price * common_vip_discount *  (SERVER_PRICE/100));
                document.querySelector('.server-price').textContent = '¥ ' + expenseprice;
		}else{
			expenseprice=0;
		}

		document.getElementById("expenseprice").value = expenseprice;
	}
	var lastprice = parseInt(total_price);


	//计算产品金额 = 总金额 - 服务费 
	var good=lastprice;
	document.querySelector('.good-price').innerText='¥ '+good;
	//最终金额=产品金额+服务费
	lastprice += expenseprice;
	
	//计算安装费 （11.5 改为到付）

    /*    if (document.querySelector('input[name="install"]').checked){
            var install_price = parseInt(total_old_price * common_vip_discount *  (LOGISTICS_PRICE/100));
            document.querySelector('.install-price').textContent = '+ ¥ ' + install_price;
            document.querySelector('#installprice').value = install_price;
            lastprice += install_price;
        }else{
            document.querySelector('.install-price').textContent = '';
            document.querySelector('#installprice').value = 0;
        }*/

      document.querySelector('#installprice').value=0;


	//计算设计费
    //2021-4-8 刘文霞修改 判断用户类型  $user_type<3&&$user_type>5 才计算设计费
    if(user_type<3||user_type>5){
 /*   if(user_type<3||user_type>5){*/
        if (document.querySelector('input[name="design"]').checked){
            var design_price = parseInt(total_old_price * common_vip_discount *  (DESIGN_PRICE/100));
            document.querySelector('.design-price').textContent = '+ ¥' + design_price;
            document.querySelector('#designprice').value = design_price;
            lastprice += design_price;
        }else{
            document.querySelector('.design-price').textContent = '';
            document.querySelector('#designprice').value = 0;
        }
   /* }else{
        document.querySelector('.design-price').textContent = '';
        document.querySelector('#designprice').value = 0;
    }*/


	lastprice = parseInt(lastprice);
	total_price = parseInt(total_price);
	
	document.getElementById("recordprice").value = lastprice;
	
	document.querySelector('#item_total_price').textContent = lastprice;

	document.getElementById("recordtotalprice").value = total_price;
	
	this.total_price = total_price;
};
Item.prototype.append = function(){
	for(var uid in this.itemList){
		if(this.itemList.hasOwnProperty(uid)){
			this.conatiner.appendChild(this.itemList[uid].node);
		}
	}
};
Item.prototype.coupon_calc = function(item_price,item_count,coupon_obj){
	var price;
	switch (coupon_obj.coupon_rule) {
		//满就减
		case 'M':
			if (item_price*item_count >= parseInt(coupon_obj.coupon_price)) {
				price = item_price*item_count-parseInt(coupon_obj.price);
			}else{
				price = item_price*item_count;
			}
			break;
		//直减
		case 'S':
			price = item_price*item_count-parseInt(coupon_obj.price);
			break;
		//折扣率
		case 'D':
			price = item_price*item_count*parseFloat(coupon_obj.price);
			break;
		//每满减
		case 'N':
			price = item_price*item_count-parseInt((item_price*item_count)/parseInt(coupon_obj.coupon_price))*parseInt(coupon_obj.price);
			break;
	}
	return price;
}
function in_array(n, arr){
	if (typeof(n)!='undefined' && typeof(arr)!='undefined') {
		for(var i=0;i<arr.length;i++){
			if (arr[i] == n) {
				return true;
			}
		}
	}
	return false;
}

var Coupon = function(coupon_obj, item){
	this.check = null;
	this.container = document.querySelector('.coupon-container');
	this.coupon = {};
	this.itemCoupon = null;
	this.tzCoupon = null;
	this.allCoupon = null;
	var type_map = {brand:'品牌优惠券', 'class':'类目优惠券', item:'单品优惠券', set:'套装优惠券', all:'全场优惠券'};
	var newDate = new Date();
	var html = '';
	for(var type in coupon_obj){
		if (!(coupon_obj.hasOwnProperty(type) && coupon_obj[type].memberCount())) {continue;}

		var html = html + '<div class="row"><div class="title">'+type_map[type]+'</div></div>';
		var c = [];
		var k = 0;
		for (var i in coupon_obj[type]) {
			if (coupon_obj[type].hasOwnProperty(i)) {
				c[k++] = coupon_obj[type][i];
			}
		}
		for(var i=0; i<c.length; i++){
			var rule_map = {
				M : '满'+c[i].coupon_price+'减'+c[i].price,
				S : '直减'+c[i].price+'元',
				D : c[i].price+'折',
				N : '每满'+c[i].coupon_price+'减'+c[i].price,
			};
			
			var start_time = parseInt(c[i].start_time)?(newDate.setTime(c[i].start_time * 1000),newDate.toLocaleDateString()):'未设置';
			var end_time = parseInt(c[i].end_time)?(newDate.setTime(c[i].end_time * 1000),newDate.toLocaleDateString()):'未设置';

			this.coupon[type+'_'+c[i].coupon_id] = c[i];

			html = html + '<label class="row coupon-item" data-uid="'+c[i].coupon_id+'" data-type="'+type+'">'+
						'<div class="coupon-left">'+
							'<div class="coupon-radio">'+
								'<input type="radio" name="coupon_'+(type==='all'?'all':((type==='set')?'set':'item'))+'_radio">'+
							'</div>'+
							'<div><img src="'+c[i].url+'"></div>'+
						'</div>'+
						'<div class="item-info">'+
							'<div class="coupon-title">'+c[i].title+'</div>'+ 
							'<div class="coupon-name">['+c[i].action_name +']'+ c[i].name+'</div>'+
							'<div class="coupon-time">起始时间：'+start_time+'; 结束时间：'+end_time+';</div>'+
							'<div class="coupon-rule">使用规则：'+rule_map[c[i].coupon_rule]+'</div>'+
						'</div>'+
					'</label>';
		}
	}
	if(html!=''){
		html = html + '<div class="row">'+
					'<div><button class="clean_coupon">不使用优惠券</button></div>'+
				  '</div>';
	}
	var that = this;
	this.container.innerHTML = html;
	if(document.addEventListener){
	    this.container.addEventListener('click', delegate_check);
	}
	if(document.attachEvent){
	    this.container.attachEvent('click', delegate_check);
	}
	function delegate_check(event){
        var target = getTarget(event);
        if(document.querySelector("button.clean_coupon").getAttribute("disabled")){
        	return false;
        }
        while (!(target.classList.contains('coupon-item') || target.classList.contains('clean_coupon') || target.tagName=='body')) {
        	target = target.parentNode || target.parentElement;
        }
        if (target.classList.contains('coupon-item')) {
            document.getElementById("ifusecoupon").value=1;
            var ifusecoupon=document.getElementById("ifusecoupon").value;
			var uid = target.dataset.uid;
			var type = target.dataset.type;
			if (type === 'all') {
				var check = that.container.querySelectorAll('input[type="radio"]:checked');
				for(var i=0;i<check.length;i++){
					if (check[i].checked && check[i].name !='coupon_all_radio') {
						check[i].checked = false;
					}
				}
				// 输入框触发
				that.itemCoupon = item.itemCoupon = null;
				that.tzCoupon = item.tzCoupon = null;
				that.allCoupon = item.allCoupon = that.coupon[type+'_'+uid];
			}else if(type === 'set'){
				var check = that.container.querySelectorAll('input[type="radio"][name="coupon_all_radio"]:checked');
				for(var i=0;i<check.length;i++){
					check[i].checked = false;
				}
				that.allCoupon = item.allCoupon = null;
				that.itemCoupon = item.tzCoupon = that.coupon[type+'_'+uid];
			}else{
				var check = that.container.querySelectorAll('input[type="radio"][name="coupon_all_radio"]:checked');
				for(var i=0;i<check.length;i++){
					check[i].checked = false;
				}
				that.allCoupon = item.allCoupon = null;
				that.tzCoupon = item.itemCoupon = that.coupon[type+'_'+uid];
			}
			item.calc();
        }else if (target.classList.contains('clean_coupon')) {
       	 document.getElementById("ifusecoupon").value=0;
        	that.clear();
			that.itemCoupon = item.itemCoupon = null;
			that.tzCoupon = item.tzCoupon = null;
			that.allCoupon = item.allCoupon = null;
			item.calc();
        }
    }
};
function getTarget(event){
    var event = event || window.event;
    var target = event.target || event.srcElement;
    return target;
}
Coupon.prototype.clear = function(){
	var check = this.container.querySelectorAll('input[type="radio"]:checked');
	for(var i=0;i<check.length;i++){
		check[i].checked = false;
	}
};

var item = new Item();
item.itemObj = detail_info;
item.userDiscount = user_discount;
item.calc();
item.append();

var c = new Coupon(coupon, item);

/*document.querySelector('input[name="install"]').onchange = function(){
	item.calc();
}*/
document.querySelector('input[name="design"]').onchange = function(){
	item.calc();
}

//3/2新增单品备注
function  check_itemmemo(e){
    var memotext=$(e).val();
    var jmz = {};
    jmz.GetLength = function(str) {
        ///<summary>获得字符串实际长度，中文2，英文1</summary>
        ///<param name="str">要获得长度的字符串</param>
        var realLength = 0, len = str.length, charCode = -1;
        for (var i = 0; i < len; i++) {
            charCode = str.charCodeAt(i);
            if (charCode >= 0 && charCode <= 128)
                realLength += 1;
            else
                realLength += 2;
        }
        return realLength;
    };
    var strlen=jmz.GetLength(memotext);
    if(strlen>100){
        alert("备注字数长度不能大于50个");
    }


}


</script>


 </body>
</html>